<?php

namespace app\common\controller\api;

use app\admin\model\CustomerServiceAccount;
use app\api\library\Auth;
use app\api\model\AppBaseConfig;
use app\api\model\Category;
use app\api\model\CustomerServiceAccountMiddle;
use app\api\model\FromConfig;
use app\api\model\User;
use think\Cache;
use think\Controller;

class Base extends Controller
{
    /**
     * @var bool
     */
    protected $country_config_id;

    /**
     * 用户对象
     */
    protected $auth;

    /**
     * 登录
     */
    protected $user;

    /**
     * 无需登录的方法,同时也就不需要鉴权了 此处放不需要鉴权的接口
     * @var array
     */
    protected $noNeedLogin = [

    ];

    /**
     * 排除前台提交过来的字段
     * @var array
     */
    protected $excludeFields = [];

    /**
     * 是否开启验证
     * @var array
     */
    protected $modelValidate = true;


    public function _initialize()
    {
        //跨域请求检测
        check_cors_request();

        //用户对象
        $this->auth = new Auth;

        //需要登陆的接口
//        if (!$this->auth->match($this->noNeedLogin)) {
//
//            $token = $this->request->header("token");
//
//            $this->country_config_id = $this->request->header("country_config_id");
//            $checktoken = $this->auth->checkToken($token);
//            if (!$checktoken) {
//                $this->error('token错误，请重新登录！', '', null, 9999);
//            }
//
//            $this->user = $this->auth->getUserInfo($token);
//
//            //获取用户最新基本信息
//            $userInfo = User::get($this->user['id']);
//            //更新用户最后使用时间
//            User::update(['prevtime' => time()], ['id' => $this->user['id']]);
//            if (empty($userInfo['status'])) {
//                $this->error('账号被禁用！', '', null, 4);
//            }
//        }
    }

    /**
     * 排除前台提交过来的字段
     * @param $params
     * @return array
     */
    protected function preExcludeFields($params)
    {
        if (is_array($this->excludeFields)) {
            foreach ($this->excludeFields as $field) {
                if (key_exists($field, $params)) {
                    unset($params[$field]);
                }
            }
        } else {
            if (key_exists($this->excludeFields, $params)) {
                unset($params[$this->excludeFields]);
            }
        }
        return $params;
    }

    /**
     * 获取应用基本配置
     */
    public function getConfig()
    {
        $params = $this->request->post();
        $appBaseId = empty($params['app_base_id']) ? 0 : $params['app_base_id'];
        $country_config_id = empty($params['country_config_id']) ? 1 : $params['country_config_id'];
        $cacheKey = 'GET_CONFIG_KEY : ' . $appBaseId . '_' . $country_config_id;
        $info = Cache::store('redis')->get($cacheKey);
//        $info = '';
        if (empty($info)) {
            $where = [
                'app_base_id' => $appBaseId,
                'country_config_id' => $country_config_id,
            ];
            $info = AppBaseConfig::where($where)->find();
            //如果应用下没有单独配置 则获取默认配置
            if (empty($info)) {
                $where = [
                    'app_base_id' => 0
                ];
                $info = AppBaseConfig::where($where)->find();
            }
            Cache::store('redis')->set($cacheKey, $info, 86400);
        }

        return $info;
    }

    public function getYnFromList()
    {
        $cacheKey = 'GET_YN_FROM_LIST_KEY : ' . $this->user['country_config_id'];
        $list = Cache::store('redis')->get($cacheKey);
        if (empty($list)) {
            $where = [
                'is_del' => 0,
                'status' => 1
            ];
            $catList = Category::field('id,nickname')->where($where)->where('pid', '=', 33)->select()->toArray();
            foreach ($catList as $key => $value) {
                switch ($this->user['country_config_id']) {
                    case 1:
                        switch ($value['id']) {
                            case 34:
                                $value['nickname'] = 'Thông tin cơ bản';
                                break;
                            case 35:
                                $value['nickname'] = 'Thông tin công việc';
                                break;
                            case 36:
                                $value['nickname'] = 'Thông tin ngân hàng';
                                break;
                        }
                        break;
                }
                $catList[$key] = $value;
            }
            $where['country_config_id'] = 1;
            $fromList = FromConfig::field('name,title,type,value,category_id,value_type,value_length,is_space_value')->where($where)->order('weight', 'desc')->select()->toArray();
            $list = [];
            foreach ($catList as $val) {
                $info = [];//初始化数组
                $info = $val;
                $info['from_list'] = [];
                foreach ($fromList as $v) {
                    if ($v['category_id'] == $val['id']) {
                        unset($v['category_id']);
                        if ($v['name'] == 'aadhaar_number') {
                            $v['title'] = 'Số Addar';
                        }
                        switch ($v['title']) {
                            case 'Name':
                                $v['title'] = 'Tên';
                                break;
                            case 'Aadhaar Number':
                                $v['title'] = '';
                                break;
                            case 'Current Address':
                                $v['title'] = 'Số Aadhaar';
                                break;
                            case 'Pincode':
                                $v['title'] = 'Pincode';
                                break;
                            case 'Sex':
                                $v['title'] = 'Giới tính';
                                break;
                            case 'Age':
                                $v['title'] = 'Tuổi';
                                break;
                            case 'Marital status':
                                $v['title'] = 'Tình trạng hôn nhân';
                                break;
                            case 'Education Attainment':
                                $v['title'] = 'Thành tựu giáo dục';
                                break;
                            case 'Email':
                                $v['title'] = 'Thư điện tử';
                                break;
                            case 'Type of work':
                                $v['title'] = 'Loại công việc';
                                break;
                            case 'Employer Name':
                                $v['title'] = 'Tên công ty';
                                break;
                            case 'Emplouer Address':
                                $v['title'] = 'Địa chỉ nhân viên';
                                break;
                            case 'Total Working Years':
                                $v['title'] = 'Tổng số năm làm việc';
                                break;
                            case 'Monthly income':
                                $v['title'] = 'Thu nhập hàng tháng';
                                break;
                            case 'Monthly household income':
                                $v['title'] = 'Thu nhập hàng tháng của gia đình';
                                break;
                            case 'IFSC code':
                                $v['title'] = 'Mã IFSC';
                                break;
                            case 'Bank Name':
                                $v['title'] = 'Tên ngân hàng';
                                break;
                            case 'Account number':
                                $v['title'] = 'Số tài khoản';
                                break;
                        }
                        $info['from_list'][] = $v;
                    }
                }
                $list[] = $info;
            }
            Cache::store('redis')->set($cacheKey, $list, 86400);
        }

        return $list;
    }

    /**
     * 获取应用提交表单配置
     */
    public function getFromList()
    {
        $params = $this->request->post();
        $cacheKey = 'GET_FROM_LIST_KEY : ' . $this->user['country_config_id'];

        $list = Cache::store('redis')->get($cacheKey);
//        $list = [];
        if (empty($list)) {
            $where = [
                'is_del' => 0,
                'status' => 1
            ];
            $catList = Category::field('id,nickname')->where($where)->where('pid', '=', 33)->select()->toArray();
            foreach ($catList as $key => $value) {
                switch ($this->user['country_config_id']) {
                    case 20:
                        switch ($value['id']) {
                            case 34:
                                $value['nickname'] = 'información_base';
                                break;
                            case 35:
                                $value['nickname'] = 'trabajo_informacion';
                                break;
                            case 36:
                                $value['nickname'] = 'información bancaria';
                                break;
                        }
                        break;
                }
                $catList[$key] = $value;
            }
            $where['country_config_id'] = $this->user['country_config_id'];
            $fromList = FromConfig::field('name,title,type,value,category_id,value_type,value_length,is_space_value')->where($where)->order('weight', 'desc')->select()->toArray();

            $list = [];
            foreach ($catList as $val) {
                $info = [];//初始化数组
                $info = $val;
                $info['from_list'] = [];
                foreach ($fromList as $v) {
                    if ($v['category_id'] == $val['id']) {
                        unset($v['category_id']);
                        $info['from_list'][] = $v;
                    }
                }
                $list[] = $info;
            }
            Cache::store('redis')->set($cacheKey, $list, 86400);
        }

        return $list;
    }

    /**
     * 根据当前登录用户  获取用户所属合作方id 客服组id  客服人员id
     */
    public function getUserPartnerField()
    {
        $cacheKey = 'GET_USER_PARTNER_FIELD_KEY : ' . $this->user['id'];
        $info = Cache::store('redis')->get($cacheKey);
        if (empty($info)) {
            $userInfo = User::get($this->user['id']);
            $accountMiddleInfo = CustomerServiceAccountMiddle::get($userInfo['customer_service_account_middle_id']);
            $accountInfo = CustomerServiceAccount::get($accountMiddleInfo['customer_service_account_id']);
            $info = [
                'partner_id' => $accountInfo['partner_id'],
                'customer_service_group_id' => $accountInfo['customer_service_group_id'],
                'customer_service_personnel_id' => $accountInfo['customer_service_personnel_id'],
            ];
            Cache::store('redis')->set($cacheKey, $info, 86400);
        }

        return $info;
    }
}